package com.ihighest.app.common.core;

import io.rong.imkit.RongContext;
import io.rong.imkit.RongIM;
import io.rong.imkit.RongIM.UserInfoProvider;
import io.rong.imkit.widget.provider.CameraInputProvider;
import io.rong.imkit.widget.provider.ImageInputProvider;
import io.rong.imkit.widget.provider.InputProvider;
import io.rong.imlib.RongIMClient.OnReceivePushMessageListener;
import io.rong.imlib.model.Conversation.ConversationType;
import io.rong.imlib.model.Group;
import io.rong.imlib.model.UserInfo;
import io.rong.notification.PushNotificationMessage;

import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;

import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Handler;
import android.os.Vibrator;
import android.util.Log;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.LocationClientOption.LocationMode;
import com.baidu.mapapi.SDKInitializer;
import com.ihighest.app.common.api.Api;
import com.ihighest.app.common.kit.AppKit;
import com.ihighest.app.common.kit.SharedPreferencesKit;
import com.ihighest.app.infox.Const;
import com.ihighest.app.infox.R;
import com.ihighest.app.infox.activity.InformationalContentActivity;
import com.ihighest.app.infox.activity.QuestionContentActivity;
import com.ihighest.app.infox.db.SQLHelper;
import com.ihighest.app.infox.im.IssueMessage;
import com.ihighest.app.infox.im.IssueMessageItemProvider;
import com.ihighest.app.infox.im.MyConversationBehaviorListener;
import com.lidroid.xutils.bitmap.callback.BitmapLoadFrom;
import com.nostra13.universalimageloader.cache.memory.impl.WeakMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.umeng.analytics.AnalyticsConfig;
import com.umeng.analytics.MobclickAgent;
import com.umeng.message.IUmengRegisterCallback;
import com.umeng.message.IUmengUnregisterCallback;
import com.umeng.message.PushAgent;
import com.umeng.message.UmengMessageHandler;
import com.umeng.message.UmengNotificationClickHandler;
import com.umeng.message.entity.UMessage;

/**
 * Applicaiton对象
 * 
 * @author Vity
 * @date 2015-7-2
 * @mail vity.1215@gmail.com
 */
public class Application extends android.app.Application {
	private static Application application = null;
	final String TAG = "Application";
	public static IUmengRegisterCallback umengRegisterCallback;
	private final List<Activity> mList = new LinkedList<Activity>();
	Activity currentAct = null;
	public static IUmengUnregisterCallback umengUnregisterCallback;
	private SQLHelper sqlHelper;
	/**
	 * 百度
	 */
	public LocationClient mLocationClient;
	public MyLocationListener mMyLocationListener;

	public TextView mLocationResult, logMsg;
	public TextView trigger, exit;
	public Vibrator mVibrator;

	/**
	 * IM输入框默认功能
	 */
	public static InputProvider.ExtendProvider[] DEFAULT_IM_PROVIDER;

	@Override
	public void onCreate() {
		super.onCreate();
		application = this;
		initImageLoader();
		/* 初始化融云框架 */
		/**
		 * OnCreate 会被多个进程重入，这段保护代码，确保只有您需要使用 RongIM 的进程和 Push 进程执行了 init。
		 * io.rong.push 为融云 push 进程名称，不可修改。
		 */
		if (getApplicationInfo().packageName.equals(AppKit.getCurProcessName(getApplicationContext()))
				|| "io.rong.push".equals(AppKit.getCurProcessName(getApplicationContext()))) {

			/**
			 * IMKit SDK调用第一步 初始化
			 */
			RongIM.init(this);
			RongIM.setOnReceivePushMessageListener(new OnReceivePushMessageListener() {
				@Override
				public boolean onReceivePushMessage(PushNotificationMessage pnm) {
					return true;
				}
			});

			/**
			 * 聊天框点击处理
			 */
			RongIM.setConversationBehaviorListener(new MyConversationBehaviorListener());

			RongIM.setUserInfoProvider(new UserInfoProvider() {
				@Override
				public UserInfo getUserInfo(String rid) {
					if (rid.equalsIgnoreCase(SharedPreferencesKit.getString(application, Const.SP_KEY_USER_RID))) {
						return new UserInfo(rid, SharedPreferencesKit.getString(application, Const.SP_KEY_USER_NAME), Uri
								.parse(SharedPreferencesKit.getString(application, Const.SP_KEY_USER_HEADER)));
					}
					JSONObject json = Api.data("member/info/r_" + rid + ".json", application);
					try {
						return new UserInfo(rid, json.getString("title"), Uri.parse(json.getString("head")));
					} catch (Exception e) {
						Log.e(TAG, e.getMessage(), e);
					}
					return new UserInfo(rid, "用户", null);
				}
			}, true);
			RongIM.setGroupInfoProvider(new RongIM.GroupInfoProvider() {
				@Override
				public Group getGroupInfo(String groupId) {
					JSONObject json = Api.data("chat/group/r_" + groupId + ".json", application);
					try {
						return new Group(groupId, json.getString("title"), Uri.parse(json.getString("image")));
					} catch (Exception e) {
						Log.e(TAG, e.getMessage(), e);
					}
					return new Group(groupId, "群组", null);
				}
			}, true);
			/**
			 * 扩展功能
			 */
			DEFAULT_IM_PROVIDER = new InputProvider.ExtendProvider[] { new ImageInputProvider(RongContext.getInstance()),// 图片
					new CameraInputProvider(RongContext.getInstance()) // 相机
			};
			RongIM.resetInputExtensionProvider(ConversationType.GROUP, DEFAULT_IM_PROVIDER);
			RongIM.resetInputExtensionProvider(ConversationType.PRIVATE, DEFAULT_IM_PROVIDER);
			// 注册问题消息模板
			RongIM.registerMessageType(IssueMessage.class);
			RongIM.registerMessageTemplate(new IssueMessageItemProvider());

		}

		/* 友盟统计 */
		MobclickAgent.setDebugMode(Const.DEBUG_MODE);

		AnalyticsConfig.enableEncrypt(true);
		MobclickAgent.updateOnlineConfig(this);

		/* 友盟推送 */
		PushAgent mPushAgent = PushAgent.getInstance(this);
		mPushAgent.setDebugMode(Const.DEBUG_MODE);
		// 消息提醒的一分钟冷却时间
		mPushAgent.setMuteDurationSeconds(60);
		// 多条通知只显示一条
		mPushAgent.setMergeNotificaiton(true);
		/**
		 * 该Handler是在BroadcastReceiver中被调用，故
		 * 如果需启动Activity，需添加Intent.FLAG_ACTIVITY_NEW_TASK
		 * */

		mPushAgent.setNotificationClickHandler(new UmengNotificationClickHandler() {
			@Override
			public void dealWithCustomAction(Context context, UMessage msg) {
				try {
					if (msg.custom.startsWith("HOT_NEWS:")) {
						// CUSTOM:HOT_NEWS:ID 实时热点
						Intent intent = new Intent();
						intent.setClass(context, InformationalContentActivity.class);
						intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						intent.putExtra("newsId", msg.custom.replace("HOT_NEWS:", ""));
						context.startActivity(intent);
					} else if (msg.custom.startsWith("NEWS:")) {
						// CUSTOM:NEWS:ID 资讯
						Intent intent = new Intent();
						intent.setClass(context, InformationalContentActivity.class);
						intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						intent.putExtra("newsId", msg.custom.replace("NEWS:", ""));
						context.startActivity(intent);
					} else if (msg.custom.startsWith("ISSUE_ANSWER:")) {
						// CUSTOM:ISSUE_ANSWER:ID 有人回答了问题
				    	System.out.println("+++++++"+msg.custom.toString());
						Intent intent = new Intent();
						intent.setClass(context, QuestionContentActivity.class);
						intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						intent.putExtra("id", msg.custom.replace("ISSUE_ANSWER:", ""));
						context.startActivity(intent);																		
						
					} else if (msg.custom.startsWith("ISSUE_ASK:")) {
						// CUSTOM:ISSUE_ASK:QID:AID:MID:TRID:TNAME 有人追问了
						// --> chat_issue_reply:qid:aid:mid
						Const.IM_EXTRA = msg.custom.replace("ISSUE_ASK", "chat_issue_reply");
						// RongIM.getInstance().startPrivateChat(context,
						// msg.custom.split(":")[4],
						// "[" + msg.custom.split(":")[5] + "]" + "的提问");

						String uri = "rong://" + getPackageName() + "/conversation/private?targetId=" + msg.custom.split(":")[4]
								+ "&title=" + "[" + msg.custom.split(":")[5] + "]" + "的提问";
						Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
						intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						intent.addCategory(Intent.CATEGORY_DEFAULT);
						context.startActivity(intent);

					} else if (msg.custom.startsWith("ISSUE_REPLY:")) {
						// CUSTOM:ISSUE_REPLY:QID:AID:MID:TRID:TNAME 有人追答了
						// --> chat_issue_ask:qid:aid:mid
						Const.IM_EXTRA = msg.custom.replace("ISSUE_REPLY", "chat_issue_ask");
						// RongIM.getInstance().startPrivateChat(context,
						// msg.custom.split(":")[4],
						// "[" + msg.custom.split(":")[5] + "]" + "的回答");
						String uri = "rong://" + getPackageName() + "/conversation/private?targetId=" + msg.custom.split(":")[4]
								+ "&title=" + "[" + msg.custom.split(":")[5] + "]" + "的回答";
						Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
						intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						intent.addCategory(Intent.CATEGORY_DEFAULT);
						context.startActivity(intent);
					} else if (msg.custom.startsWith("ISSUE_ACCEPT:")) {
						// CUSTOM:ISSUE_ACCEPT:ID 采纳了您的答案
						Intent intent = new Intent();
						intent.setClass(context, QuestionContentActivity.class);
						intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						intent.putExtra("id", msg.custom.replace("ISSUE_ACCEPT:", ""));
						context.startActivity(intent);
					} else if (msg.custom.startsWith("ISSUE_NOTIFY:")) {
						// CUSTOM:ISSUE_NOTICE:ID 谁发了问题
						Intent intent = new Intent();
						intent.setClass(context, QuestionContentActivity.class);
						intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						intent.putExtra("id", msg.custom.replace("ISSUE_NOTIFY:", ""));
						context.startActivity(intent);
					}
				} catch (Exception ex) {
					Log.e(TAG, ex.getMessage(), ex);
				}
			}

		});
		mPushAgent.setMessageHandler(new UmengMessageHandler() {
			@Override
			public void dealWithCustomMessage(Context context, UMessage message) {
				if (message.custom != null && message.custom.startsWith("NEW_SITE_MSG:")) {

					// 发送广播通知铃铛改变
					Intent mIntent = new Intent(Const.CHANGECOUNT);
					Const.UNREADMESSAGE++;
					// 发送广播
					sendBroadcast(mIntent);

					// 您有新的站内消息
					Log.d(TAG, "--->>>> 您有新的站内消息");
				} else if (message.custom != null && message.custom.startsWith("NEW_CHANNEL_UP:")) {
					// 新频道上线
					Log.d(TAG, "--->>>> 新频道上线");
				}
				super.dealWithCustomMessage(context, message);
			}

			@Override
			public void dealWithNotificationMessage(Context context, UMessage message) {
				super.dealWithNotificationMessage(context, message);
			}
		});
		umengRegisterCallback = new IUmengRegisterCallback() {

			@Override
			public void onRegistered(String registrationId) {
				Log.d(TAG, "Umeng onRegistered RegistrationId -->>> " + registrationId);
				new Thread(new Runnable() {
					@Override
					public void run() {
						try {
							PushAgent.getInstance(getApplicationContext()).addAlias("INFOX_ANDROID", "P_TYPE");
						} catch (Exception e) {
							Log.e(TAG, e.getMessage(), e);
						}
					}
				}).start();
			}

		};
		mPushAgent.setRegisterCallback(umengRegisterCallback);

		umengUnregisterCallback = new IUmengUnregisterCallback() {

			@Override
			public void onUnregistered(String registrationId) {
				Log.d(TAG, "Umeng onUnregistered RegistrationId -->>> " + registrationId);

				new Thread(new Runnable() {
					@Override
					public void run() {
						try {
							PushAgent.getInstance(getApplicationContext()).removeAlias("INFOX_ANDROID", "P_TYPE");
						} catch (Exception e) {
							Log.e(TAG, e.getMessage(), e);
						}
					}
				}).start();
			}
		};
		mPushAgent.setUnregisterCallback(umengUnregisterCallback);
		// 百度相关
		SDKInitializer.initialize(this);
		LocationClientOption option = new LocationClientOption();
		option.setLocationMode(LocationMode.Hight_Accuracy);//
		// 可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
		option.setCoorType("bd09ll");// 可选，默认gcj02，设置返回的定位结果坐标系
		int span = 1000;
		option.setScanSpan(span);// 可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
		option.setIsNeedAddress(true);// 可选，设置是否需要地址信息，默认不需要
		option.setOpenGps(true);// 可选，默认false,设置是否使用gps
		option.setLocationNotify(true);// 可选，默认false，设置是否当gps有效时按照1S1次频率输出GPS结果
		option.setIsNeedLocationDescribe(true);//
		// 可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
		option.setIsNeedLocationPoiList(true);//
		// 可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
		option.setIgnoreKillProcess(false);//
		// 可选，默认false，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认杀死
		option.SetIgnoreCacheException(false);// 可选，默认false，设置是否收集CRASH信息，默认收集
		option.setEnableSimulateGps(false);// 可选，默认false，设置是否需要过滤gps仿真结果，默认需要
		mLocationClient = new LocationClient(this.getApplicationContext());
		mLocationClient.setLocOption(option);
		mMyLocationListener = new MyLocationListener();
		mLocationClient.registerLocationListener(mMyLocationListener);
		mVibrator = (Vibrator) getApplicationContext().getSystemService(Context.VIBRATOR_SERVICE);
		if (getApplicationInfo().packageName.equals(AppKit.getCurProcessName(getApplicationContext()))) {
			final Handler handler = new Handler();
			Runnable runnable = new Runnable() {
				@Override
				public void run() {
					mLocationClient.start();
					handler.postDelayed(this, 10 * 60 * 1000);
				}
			};
			handler.postDelayed(runnable, 1 * 1000);
		}
	}

	/**
	 * 实现实时位置回调监听
	 */
	public class MyLocationListener implements BDLocationListener {

		@Override
		public void onReceiveLocation(BDLocation location) {
			mLocationClient.stop();
			LinkedHashMap<String, Object> map = new LinkedHashMap<String, Object>();
			map.put("last", location.getTime());
			map.put("locType", location.getLocType());
			map.put("latitude", location.getLatitude());
			map.put("lontitude", location.getLongitude());
			map.put("radius", location.getRadius());
			map.put("loc", location.getLatitude() + ":" + location.getLatitude() + ":" + location.getLongitude());
			map.put("city", location.getCity());
			map.put("cityCode", location.getCityCode());
			if (location.getLocType() == BDLocation.TypeGpsLocation) {// GPS定位结果
				map.put("gps_speed", location.getSpeed());
				map.put("gps_satellite", location.getSatelliteNumber());
				map.put("gps_altitude", location.getAltitude());
				map.put("gps_direction", location.getDirection());
				map.put("gps_addr", location.getAddrStr());
				map.put("describe", "GPS定位成功");
			} else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {// 网络定位结果
				map.put("network_addr", location.getAddrStr());
				map.put("network_address", location.getAddress().country + location.getAddress().province + location.getAddress().city
						+ location.getAddress().district);
				map.put("network_operationers", location.getOperators());
				map.put("describe", "网络定位成功");
			} else if (location.getLocType() == BDLocation.TypeOffLineLocation) {// 离线定位结果
				map.put("describe", "离线定位成功，离线定位结果也是有效的");
			} else if (location.getLocType() == BDLocation.TypeServerError) {
				map.put("describe", "服务端网络定位失败，可以反馈IMEI号和大体定位时间到loc-bugs@baidu.com，会有人追查原因");
			} else if (location.getLocType() == BDLocation.TypeNetWorkException) {
				map.put("describe", "网络不同导致定位失败，请检查网络是否通畅");
			} else if (location.getLocType() == BDLocation.TypeCriteriaException) {
				map.put("describe", "无法获取有效定位依据导致定位失败，一般是由于手机的原因，处于飞行模式下一般会造成这种结果，可以试着重启手机");
			}
			map.put("locationdescribe", location.getLocationDescribe());
			map.put("poi", location.getPoiList());
			SharedPreferencesKit.putJsonObject(application, Const.SP_KEY_BD_LOCAITON, new JSONObject(map));
			Log.d(TAG, SharedPreferencesKit.getJsonObject(application, Const.SP_KEY_BD_LOCAITON).toString());
		}
	}

	// add Activity
	public void addActivity(Activity activity) {
		mList.add(activity);
		currentAct = activity;
	}

	public void exit() {
		try {
			for (Activity activity : mList) {
				if (activity != null)
					activity.finish();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			System.exit(0);
		}
	}

	public static Application getInstance() {
		if (null == application) {
			application = new Application();
		}
		return application;
	}

	/**
	 * 初始化imageloader
	 * 
	 * 
	 * @author lkx Created at 2015-10-10 下午5:53:08
	 */
	public static void initImageLoader() {
		DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder().showImageForEmptyUri(R.drawable.infox_img_loadrong)
				.showImageOnFail(R.drawable.infox_img_loadrong).showImageOnLoading(R.drawable.infox_img_loadrong)
				.imageScaleType(ImageScaleType.EXACTLY).cacheInMemory(true).cacheOnDisc(true).bitmapConfig(Bitmap.Config.RGB_565).build();
		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getInstance()).defaultDisplayImageOptions(defaultOptions)
				.discCacheSize(50 * 1024 * 1024)//
				.discCacheFileCount(100)// 缓存几张图片
				.threadPoolSize(3)// 线程池个数，建议1~5
				.memoryCache(new WeakMemoryCache()).writeDebugLogs().build();
		ImageLoader.getInstance().init(config);
	}

	/** 获取数据库Helper */
	public SQLHelper getSQLHelper() {
		if (sqlHelper == null)
			sqlHelper = new SQLHelper(application);
		return sqlHelper;
	}
}
